package org.ruanjj.multithread.JUC;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
        //*******add  remove*********
        //1. add  放入的元素个数超过容器要求的个数就报错
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        //System.out.println(blockingQueue.add("x"));

        //2. remove 当容器中没有元素去取的时候就会报错
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
       // System.out.println(blockingQueue.remove());

        //*******offer poll*********
        //1. offer  放入的元素个数超过容器要求的个数时，不报错，直接返回false，表示加数据没成功
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        System.out.println(blockingQueue.offer("x"));

        //2. remove 当容器中没有元素去取的时候不会报错，只会返回null，能取到就返回取到的值
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());


        System.out.println("*******put take*********");
        //1.put()
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //blockingQueue.put("x");  //超过容器要求个数时它会一直阻塞，直到能插入为止

        //2.take
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
     //   System.out.println(blockingQueue.take());//这里取不到也会一直阻塞着，直到能取到为止

        System.out.println("*******offer poll*********");
        //1.offer(e, time, timeUtil)
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("b", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("c", 2L, TimeUnit.SECONDS));
        //等2秒钟，可以往里加的时候就加进去
        System.out.println(blockingQueue.offer("X", 2L, TimeUnit.SECONDS));

        //2.poll(time, timeUtil)
        System.out.println(blockingQueue.poll(2l, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2l, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2l, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2l, TimeUnit.SECONDS));
    }
}
